import { useEffect, useState } from 'react';
import { Upload, ModalProps, message, Form, Input } from 'antd';
import { StyledUploadBox } from './styles';
import Modals from '@/components/modals/Modals';
import { SvgIcon } from '@/components/icon';
import { GetListType } from '@/common/types';

const { Dragger } = Upload;

interface Props extends ModalProps {
  open?: boolean;
  onCancel?: () => void;
  onFileOk?: (taskName: string, file: File) => void;
  uploadError?: string;
  isSubmitting?: boolean;
}

const UploadModal = ({ open = true, onCancel, onFileOk, uploadError, isSubmitting = false, ...props }: Props) => {
  const [file, setFile] = useState<File>();
  const [form] = Form.useForm();
  const [fileError, setFileError] = useState(false);
  const [messageApi, contextHolder] = message.useMessage();

  useEffect(() => {
    if (uploadError) {
      setFileError(true);
    } else {
      setFileError(false);
    }
  }, [uploadError]);

  const handleUpload = (files: File) => {
    if (!files.name.endsWith('.xlsx')) {
      messageApi.error('文件格式不正确,只支持xlsx文件');
      return;
    }

    if (files?.size && files.size > 20 * 1024 * 1024) {
      messageApi.error('文件大小不能超过20M');
      return;
    }
    setFile(files);
    setFileError(false); // 清除之前的错误状态
    form.setFieldsValue({ file: files });
    return false;
  };

  const handleRemove = () => {
    setFile(undefined);
    setFileError(false); // 清除错误状态
    form.setFieldsValue({ file: undefined });
  };

  const handleOk = async () => {
    if (isSubmitting) return;
    try {
      const values = await form.validateFields();
      console.log('form.validateFields()===========', values);
      onFileOk && onFileOk(values.taskName, values.file);
    } catch (errorInfo) {
      console.error('Validation failed:', errorInfo);
    }
  };

  const handleClose = () => {
    setFile(undefined);
    setFileError(false);
    form.resetFields();
  };

  const onFinish = (values: GetListType) => {
    if (values.dataset_tag.trim() === '') {
      messageApi.warning('不允许空文件类型上传!');
      return;
    }
  };

  return (
    <Modals
      {...props}
      title={'新建测试任务'}
      open={open}
      onCancel={onCancel}
      onOk={handleOk}
      afterClose={handleClose}
      okText={isSubmitting ? '创建中...' : '创建'}
    >
      <StyledUploadBox>
        {contextHolder}
        <Form layout="vertical" form={form} onFinish={onFinish}>
          <Form.Item label="任务名称" name={'taskName'} style={{ marginBottom: 0 }} rules={[{ required: true, message: '请输入任务名称' }]} className="relative">
            <Input maxLength={20} showCount />
          </Form.Item>
          <Form.Item
            label={
              <div className="flex items-center justify-between w-full">
                <span>上传测试文件</span>
                <a
                  href="/api/openapi/v2/app/test/file/template"
                  className="!text-@brand-color text-sm"
                  onClick={(e) => e.stopPropagation()} // 阻止事件冒泡
                  style={{ pointerEvents: 'auto' }} // 确保链接可点击
                >
                  下载测试模板
                </a>
              </div>
            }
            name={'file'} style={{ marginBottom: 0 }} rules={[{ required: true, message: '请上传测试文件' }]}>
            {file && !fileError ? (
              <div className="flex h-[110px] items-center justify-between rounded-[16px] bg-[#ECEFF8] py-[16px] pl-[30px] pr-[11px]">
                <div className="text-gray-800">{file.name}</div>
                <button
                  className="!text-@error-color hover:text-red-700 transition-colors"
                  onClick={handleRemove}
                >
                  删除
                </button>
              </div>
            ) : (
              <Dragger maxCount={1} beforeUpload={handleUpload} accept={'.xlsx'}>
                {file && fileError ? (
                  <div className="flex h-[94px] items-center justify-between rounded-[16px] bg-[#ECEFF8] pl-[30px] pr-[11px]">
                    <div className='text-left'>
                      <div>{file.name}</div>
                      <div>
                        {uploadError?.includes('文件验证失败') && fileError && (
                          <p className="mt-1 text-sm text-[var(--warning-color)]">
                            文件内容格式错误，请按模板规范填写
                          </p>
                        )}
                      </div>
                    </div>

                    <a className="text-[var(--brand-color)]" >
                      重新上传
                    </a>
                  </div>
                ) : (
                  // 正常上传状态内容
                  <div className="flex h-[78px] flex-col items-center justify-center">
                    <SvgIcon icon="icon-upload" size={32} />
                    <div className="mt-1 text-center text-[#474C5F]">上传XLSX文件</div>
                  </div>
                )}
              </Dragger>
            )}
          </Form.Item>
        </Form>
      </StyledUploadBox>
    </Modals>
  );
};

export default UploadModal;
